/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pwned.memory;

import com.sun.jna.Native;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.Tlhelp32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.win32.W32APIOptions;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Zlobniy
 */
public abstract class MyKernel32Impl {

    static Kernel32 kernel32 = (Kernel32)Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS);
    
    
    static List<Long> FindProcessId(String processName)
    {
        // This Reference will contain the processInfo that will be parsed to recover the ProcessId
        Tlhelp32.PROCESSENTRY32.ByReference processInfo = new Tlhelp32.PROCESSENTRY32.ByReference();
        List<Long> pids = new ArrayList<Long>();
        // This Handle allows us to parse the process map
        WinNT.HANDLE processesSnapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0L));
        if(processesSnapshot == kernel32.INVALID_HANDLE_VALUE)
        {
            return null;
        }
        
        try{// This will parse all the processes to find the process id corresponding to the process name
            kernel32.Process32First(processesSnapshot, processInfo);
            if(processName.equals(Native.toString(processInfo.szExeFile)))
            {
                pids.add(processInfo.th32ProcessID.longValue());
                return pids;
            }
            
            while(kernel32.Process32Next(processesSnapshot, processInfo))
            {
                if(processName.equals(Native.toString(processInfo.szExeFile)))
                {
                    pids.add(processInfo.th32ProcessID.longValue());
                }
            }
            
            return pids;
        }
        finally
        {
            kernel32.CloseHandle(processesSnapshot);
        }
        
    }
    
    
}
